/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package library;

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.util.List;
import java.util.Set;

/**
 *
 * @author jakob
 */
public class XmlWriter {
    static public void saveLibrary(Library lib, File libFile)
    {
        try{
            Set<User> users = lib.getUsers();
            List<Item> items = lib.getAvailableItems();
            
            FileWriter fstream = new FileWriter(libFile);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write("<library>\n");
            
            for(User u:users){
                writeUser(u, out);
            }
                
            
            for(int i = 0; i < items.size(); i++)
                writeItem(items.get(i), out);
            
            out.write("</library>");
            
            out.close();
        }
        catch(Exception e)
        {
            
        }
    }

    static private void writeUser(User u, BufferedWriter out)
    {
        try
        {
            Item[] items = {};
            items = u.getItems().toArray(items);
            
            out.write("<user>\n");
            out.write("<id>" + u.getId() + "</id>\n");
            out.write("<name>" + u.getName() + "</name>\n");
            out.write("<type>" + u.getType().toString() + "</type>\n");
            
            if(items.length > 0)
            {
                out.write("<items>\n");

                for(int i = 0; i < items.length; i++)
                    writeItem(items[i], out);


                out.write("</items>\n");
            }
            
            out.write("</user>\n");
        }
        catch(Exception e)
        {
            
        }
    }
    
    static private void writeItem(Item i, BufferedWriter out)
    {
        try
        {
            out.write("<item>\n");
            out.write("<id>" + i.getId() + "</id>\n");
            out.write("<type>" + i.getType().toString() + "</type>\n");
            out.write("<title>" + i.getTitle() + "</title>\n");
            if(i.isCheckedOut()){
                out.write("<due_date>" +i.getDueDate().getTime()+"</due_date>\n");
            }
            out.write("<description>" + i.getDescription() + "</description>\n");
            out.write("</item>\n");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }       
    }
}


